package com.liaoye.hellocustomview.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathDashPathEffect;
import android.graphics.PathMeasure;
import android.os.Build;
import android.view.View;

import androidx.annotation.RequiresApi;

import com.liaoye.hellocustomview.util.DPUtil;

public class DashBoardView extends View {
    private Paint mPaint;
    private Path mPath;
    private Path mRect;
    private Path mLinePath;
    private Path mIndicatorPath;
    private int radius = 0;
    private float angle = 120;

    {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        mPaint = new Paint();
        mPaint.setColor(Color.BLACK);
        mPaint.setStrokeWidth(DPUtil.dpToPix(2));
        mPaint.setStyle(Paint.Style.STROKE);
        mPath = new Path();
        mRect = new Path();
        mRect.addRect(0, 0, 5, 30, Path.Direction.CW);
        mLinePath = new Path();
        mIndicatorPath = new Path();
    }

    public DashBoardView(Context context) {
        super(context);
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        int centerX = width / 2;
        int centerY = height / 2;
        radius = width / 3;

        //先画表盘
        mPath.addArc(centerX - radius, centerY - radius, centerX + radius, centerY + radius,
                angle, 360 - angle / 2);

        mLinePath.addArc(centerX - radius, centerY - radius, centerX + radius, centerY + radius,
                angle, 360 - angle / 2);
        canvas.drawPath(mPath, mPaint);

        //再画表刻度
        PathMeasure pathMeasure = new PathMeasure(mPath, false);
        float length = pathMeasure.getLength();
        float space = (length - 5) / 20;
        PathDashPathEffect dashPathEffect = new PathDashPathEffect(mRect, space, 0, PathDashPathEffect.Style.MORPH);
        mPaint.setPathEffect(dashPathEffect);
        canvas.drawPath(mLinePath, mPaint);
        mPaint.setPathEffect(null);

        mIndicatorPath.moveTo(centerX, centerY);
//        mIndicatorPath.lineTo(centerX, centerY - radius);

        mIndicatorPath.lineTo(centerX + Double.valueOf(Math.cos(Math.toRadians(getCurrentAngle(2))) * radius).floatValue(), centerY + Double.valueOf(Math.sin(Math.toRadians(getCurrentAngle(2))) * radius).floatValue());
        canvas.drawPath(mIndicatorPath, mPaint);
    }

    private double getCurrentAngle(int currentIndex) {
        return angle + ((double) (360 - angle / 2 - angle) / 20 * currentIndex);
    }


}
